﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Net.Mime;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using GurLoader.Util;
using GurLoader.View;

namespace GurLoader.ViewModel
{
    public class PreferencesViewModel : INotifyPropertyChanged, IDisposable
    {
        public event EventHandler RequestClose;
        public event PropertyChangedEventHandler PropertyChanged;

        public Preferences.GurLoaderPreferences AppPreferences { get; private set; }
        private ICommandManager CommandMngr { get; set; }

        public PreferencesViewModel(Preferences.GurLoaderPreferences appPreferences, ICommandManager commandMngr)
        {
            AppPreferences = appPreferences;
            CommandMngr = commandMngr;

            AppPreferences.BeginEdit();
            AppPreferences.PropertyChanged += OnPreferencesPropertyChanged;
        }

        protected void OnPreferencesPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if ( e.PropertyName.Equals("IsDirty") )
                CommandMngr.InvalidateRequerySuggested();
        }

        public ICommand OkCommand
        {
            get
            {
                return new DelegateCommand
                {
                    CanExecuteFunc = () =>
                    {
                        return AppPreferences.IsDirty;
                    },
                    CommandAction = () =>
                    {
                        AppPreferences.EndEdit();
                        AppPreferences.Save();
                        if ( RequestClose != null )
                            RequestClose(this, EventArgs.Empty);
                    }
                };
            }
        }

        public ICommand CancelCommand
        {
            get
            {
                return new DelegateCommand
                {
                    CommandAction = () =>
                    {
                        AppPreferences.CancelEdit();

                        if (RequestClose != null)
                            RequestClose(this, EventArgs.Empty);
                    }
                };
            }
        }


        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool isDisposing)
        {
            if (isDisposing)
            {
                AppPreferences.PropertyChanged -= OnPreferencesPropertyChanged;
            }
        }
    }
}
